package tk.hongbo.server.codec

import android.media.MediaCodec
import android.media.MediaCodec.BufferInfo
import android.media.MediaFormat
import android.view.Surface
import java.nio.ByteBuffer


/**
 * 解码器
 * Created by HongboZhao on 2022/1/27.
 */
object Decoder {

    private const val width = 1280
    private const val height = 960

    private lateinit var codec: MediaCodec

    fun openDecode(surface: Surface) {
        codec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_HEVC)
        val mediaFormat =
            MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_HEVC, width, height)
        mediaFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, width * height)
        codec.configure(mediaFormat, surface, null, 0)
        codec.start()
    }

    fun decodeAndPlayBack(input: ByteArray, offset: Int, length: Int) {
        //获取喂数据的ByteBuffer数组
        val inputBuffers: Array<ByteBuffer> = codec.inputBuffers

        /*以下特别注意,TIME_OUT建议设置成0,设置非0很多机子,出现卡死在此句代码,设置成0的代价只是丢帧 */
        val inputBuffersIndex: Int = codec.dequeueInputBuffer(0)
        if (inputBuffersIndex >= 0) {
            val inputBuffer = inputBuffers[inputBuffersIndex]
            inputBuffer.clear()
            inputBuffer.put(input, offset, length)
            //填充好数据以后,提交通知解码器解码,这几个参数待研究
            codec.queueInputBuffer(inputBuffersIndex, 0, length, 0, 0)
        }
        //释放缓存空间
        val bufferInfo = BufferInfo()
        var outputBufferIndex: Int = codec.dequeueOutputBuffer(bufferInfo, 0)
        while (outputBufferIndex >= 0) {
            codec.releaseOutputBuffer(outputBufferIndex, true)
            outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 0)
        }
    }
}